﻿using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;

namespace Bookvar.Common
{
	public static class RecentFiles
	{
		private static readonly List<string> recentFiles = new List<string>();
		private static readonly string recentFilesPath;


		[SuppressMessage( "Microsoft.Performance",
			"CA1810:InitializeReferenceTypeStaticFieldsInline" )]
		static RecentFiles()
		{
			string bookvarFolder = FileUtility.BookvarLocalApplicationFolder;
			recentFilesPath = Path.Combine( bookvarFolder, "RecentFiles.dat" );

			Mutex mutex = new Mutex( false, "Recent files access" );
			mutex.WaitOne();
			if ( File.Exists( recentFilesPath ) )
			{
				recentFiles.AddRange( File.ReadAllLines( recentFilesPath ) );
			}
			else
			{
				File.Create( recentFilesPath );
			}
			mutex.ReleaseMutex();
		}

		public static ICollection<string> All
		{
			get { return recentFiles; }
		}

		public static void AddFileToRecent( string filePath )
		{
			recentFiles.Remove( filePath );
			recentFiles.Insert( 0, filePath );
			if ( recentFiles.Count > 10 )
			{
				for ( int i = 10; i < recentFiles.Count; i++ )
				{
					recentFiles.RemoveAt( i );
				}
			}
			PersistRecentFiles();
		}

		private static void PersistRecentFiles()
		{
			using ( StreamWriter writer = new StreamWriter( recentFilesPath ) )
			{
				foreach ( string recentFile in recentFiles )
				{
					writer.WriteLine( recentFile );
				}
			}
		}
	}
}